<?php
namespace App\Console\Commands\Env;

use Symfony\Component\Console\Attribute\AsCommand;
use Jammiest\SwigeCore\Console\Commands\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;

#[AsCommand(
    name: 'key:generate',
    description: '生成应用加密密钥'
)]
class GenerateKeyCommand extends Command
{
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('生成应用密钥');

        try {
            $envFile = base_path('.env');
            $key = 'base64:' . base64_encode(random_bytes(32));

            if (!file_exists($envFile)) {
                throw new \RuntimeException('.env 文件不存在');
            }

            $content = file_get_contents($envFile);

            if (preg_match('/^APP_KEY=/m', $content)) {
                $content = preg_replace('/^APP_KEY=.*$/m', 'APP_KEY='.$key, $content);
            } else {
                $content .= "\nAPP_KEY=".$key."\n";
            }

            file_put_contents($envFile, $content);
            $io->success('应用密钥已生成并更新到 .env 文件');
            $io->text('<comment>APP_KEY: ' . $key . '</comment>');

            return Command::SUCCESS;

        } catch (\Exception $e) {
            $io->error('生成密钥失败: ' . $e->getMessage());
            return Command::FAILURE;
        }
    }
}